package com.gonsin.i18n.logic.services;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SaveThread extends Thread implements InitializingBean {

    private Map<String, SavingHolder> savingHolders;

    public SaveThread() {
        this.savingHolders = new ConcurrentHashMap<>();
    }

    public void save(String projectName, String lang, File langFile, String json){
        synchronized (SaveThread.this){
            savingHolders.put(langFile.getAbsolutePath(), new SavingHolder(langFile, json));
        }
    }

    @SneakyThrows
    @Override
    public void run() {
        while(true){
            Thread.sleep(10000);
            SavingHolder holder = null;
            try {
                synchronized (SaveThread.this){
                    Set<String> keys = savingHolders.keySet();
                    if(CollectionUtils.isEmpty(keys)){
                        continue;
                    }
                    String key = keys.stream().findFirst().orElse(null);
                    holder = savingHolders.remove(key);
                    if(holder == null){
                        continue;
                    }
                    FileUtils.writeStringToFile(holder.langFile, holder.json, "UTF8");
                }
            } catch (Exception ex){
                log.error(ex.toString(), ex);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        start();
    }

    /**
     *
     */
    class SavingHolder {

        private File langFile;

        private String json;

        public SavingHolder(File langFile, String json) {
            this.langFile = langFile;
            this.json = json;
        }
    }


    private static SaveThread instance;
    public static SaveThread getInstance(){
        if(instance == null){
            synchronized (SaveThread.class){
                if(instance == null){
                    instance = new SaveThread();
                    try {
                        instance.afterPropertiesSet();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return instance;
    }
}
